package com.huayue.dao;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.huayue.config.AliPayConfig;
import com.huayue.entity.AliPayAccept;
import com.mysql.DBHelper;

/**
 * 支付宝支付方法
 */
public class AliPayDao {
    /**
     * 发送支付请求
     * 
     * @return
     */
    public void SendAliPay(String orderNumber, BigDecimal total_amount, String orderType, String return_url,
        String notify_url, HttpServletResponse response) throws AlipayApiException, IOException {
        AlipayClient alipayClient =
            new DefaultAlipayClient(AliPayConfig.gatewayUrl, AliPayConfig.app_id, AliPayConfig.private_key,
                AliPayConfig.format, AliPayConfig.charset, AliPayConfig.public_key, AliPayConfig.sign_type);
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(return_url);
        alipayRequest.setNotifyUrl(notify_url);
        AlipayTradePayModel model = new AlipayTradePayModel();
        model.setProductCode("FAST_INSTANT_TRADE_PAY");
        model.setOutTradeNo(orderNumber);
        model.setSubject(orderType);
        model.setTotalAmount(total_amount.toString());
        model.setBody(orderType);
        model.setTimeoutExpress("5m");
        alipayRequest.setBizModel(model);

        String form = alipayClient.pageExecute(alipayRequest).getBody();
        response.setContentType("text/html;charset=utf-8");
        response.getWriter().write(form);
        response.getWriter().flush();
        response.getWriter().close();
    }

    /**
     * 接收支付宝回复的请求
     * 
     * @param request
     * @return
     * @throws AlipayApiException
     */
    public boolean AcceptAliPay(HttpServletRequest request) throws AlipayApiException {
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext();) {
            String name = (String)iter.next();
            String[] values = (String[])requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            params.put(name, valueStr);
        }
        boolean signVerified =
            AlipaySignature.rsaCheckV1(params, AliPayConfig.public_key, AliPayConfig.charset, AliPayConfig.sign_type);
        // 返回界面
        if (signVerified) {
            return true;
        } else {
            return false;
        }
    }

    public int insert(AliPayAccept entity) {
        String sql = "insert into alipay(out_trade_no,gmt_create,gmt_payment,notify_time,subject,"
            + "buyer_id,invoice_amount,total_amount,trade_status,trade_no,"
            + "buyer_pay_amount,temp_order_id) values(?,?,?,?,?,?,?,?,?,?,?,?)";
        return DBHelper.executeUpdate(sql, entity.getOut_trade_no(), entity.getGmt_create(), entity.getGmt_payment(),
            entity.getNotify_time(), entity.getSubject(), entity.getBuyer_id(), entity.getInvoice_amount(),
            entity.getTotal_amount(), entity.getTrade_status(), entity.getTrade_no(), entity.getBuyer_pay_amount(),
            entity.getOrderNumber());
    }

    public List<Map<String, Object>> findPayByOrderNumber(String orderNumber) {
        return DBHelper.executeQuery("select * from alipay where out_trade_no = ?", orderNumber);
    }
}
